package com.weizhu.swufer.core.monitor;

import com.weizhu.swufer.core.grpc.RemoteCacheManager;
import com.weizhu.swufer.core.metrics.MetricsManager;
import com.weizhu.swufer.core.metrics.RpcMetrics;
import com.weizhu.swufer.core.rpc.RpcEngine;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.Map;
import java.util.concurrent.ConcurrentMap;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledThreadPoolExecutor;
import java.util.concurrent.TimeUnit;

public class RpcMonitor {

    private final static Logger logger = LoggerFactory.getLogger(RpcMonitor.class);

    private volatile static RpcMonitor instance;

    private RpcMonitor(){
        init();
    }

    public static RpcMonitor getInstance(){
        if (instance == null){
            synchronized (RpcMonitor.class){
                if (instance == null){
                    instance = new RpcMonitor();
                }
            }
        }
        return instance;
    }

    private void init(){
        ScheduledThreadPoolExecutor executor = (ScheduledThreadPoolExecutor) Executors.newScheduledThreadPool(1);
        executor.scheduleAtFixedRate(()->{
            ConcurrentMap<String, RpcMetrics> serverMetricsMap = MetricsManager.getServerMetrics();
            for (Map.Entry<String, RpcMetrics> entry : serverMetricsMap.entrySet()) {
                RpcMetrics rpcMetrics = entry.getValue();
                if (rpcMetrics.failOverThreshold()){
                    RemoteCacheManager.getInstance().removeRemoteServiceCache(entry.getKey());
                    rpcMetrics.clear();
                }
            }
        },0,1, TimeUnit.SECONDS);
    }

}
